package com.hsy.bibc.modules.waste;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.deparse.dpframe.ui.widget.DPCircleImageView;
import com.deparse.dpframe.utils.DPGsonUtil;
import com.deparse.dpframe.utils.DPHttpUtil;
import com.deparse.dpframe.utils.DPLogUtil;
import com.deparse.dpframe.utils.DPPicassoUtil;
import com.hsy.bibc.R;
import com.hsy.bibc.common.Consts;
import com.hsy.bibc.modules.common.CommonBaseActivityWithSimpleActionBar;
import com.hsy.bibc.modules.main.MainActivity;
import com.hsy.bibc.modules.order.EditTextExt;
import com.hsy.bibc.utils.CommonUtils;
import com.hsy.bibc.utils.HttpUtil;
import com.hsy.bibc.utils.VolleyLoadPicture;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/6/3.
 */
public class WasteActivity extends CommonBaseActivityWithSimpleActionBar {


    private ExpandableListView expand_list;
    private AdapterListView detailGoodsAdapter;
    private AfterCodeGsonData.Result listData;
    private TextView nick_name, score;

    private int openGroup = -1;

    private DPHttpUtil.HttpCallback httpCallBack = new DPHttpUtil.HttpCallback() {
        @Override
        public void onSuccess(int what, String response) {
            if (0 == what) {
                listData = DPGsonUtil.fromJson(response, AfterCodeGsonData.Result.class);
                nick_name.setText(listData.getUser().getNickname());
                score.setText(listData.getUser().getScore() + "积分");
//                DPPicassoUtil.with(AfterCodeActivity.this).load(listData.getUser().getAvatar()).into(avatar);
                VolleyLoadPicture vlp = new VolleyLoadPicture(WasteActivity.this, avatar);
                vlp.getmImageLoader().get(listData.getUser().getAvatar(), vlp.getOne_listener());
                detailGoodsAdapter = new AdapterListView(WasteActivity.this, listData);
                expand_list.setAdapter(detailGoodsAdapter);
                if (listData.getWaste().size() > 0) {
                    for (int i = 0; i < listData.getWaste().size(); i++) {

                        expand_list.expandGroup(0);
                        openGroup = 0;
                    }
                } else {
                    DPLogUtil.d("listData.getWaste()==0");
                }

            } else if (1 == what) {
//                OrderIntentJsonData orderIntentJsonData = DPGsonUtil.fromJson(response, OrderIntentJsonData.class);
                startActivity(WasteConfirmActivity.class, "1", response);

            }

//            expand_list.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
//                @Override
//                public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
//                    return true;
//                }
//            });


            CommonUtils.hideProgressDialog();

            getContentView().setVisibility(View.VISIBLE);
        }

        @Override
        public void onError(int what, int type, VolleyError error) {
            CommonUtils.hideProgressDialog();
        }

        @Override
        public void onMsgError(int what, int type, String msg) {
            if (0 == what) {
                if (Consts.TYPE_CODE_ERROR == type) {
                    CommonUtils.showErrorMsgDialog(WasteActivity.this, msg);
                }
            } else if (1 == what) {
                CommonUtils.hideProgressDialog();
            }

        }
    };
    private TextView finish;
    private DPCircleImageView avatar;

    private String extra;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_waste);

        setTitle(R.string.title_detail);

        getContentView().setVisibility(View.GONE);

        expand_list = F(R.id.expand_list);
        finish = F(R.id.finish);

        extra = getActivityStartExtra()[0];

        finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isEmpty = true;
                List<String> qtyList = new ArrayList<String>();
                for (int i = 0; i < listData.getWaste().size(); i++) {
                    for (int j = 0; j < listData.getWaste().get(i).getChildren().size(); j++) {
                        String qty = listData.getWaste().get(i).getChildren().get(j).getQty();
                        qtyList.add(qty);
                    }
                }
                for (int i = 0; i < qtyList.size(); i++) {

                    if (!"0".equals(qtyList.get(i))) {
                        isEmpty = false;
                    }
                }
                if (isEmpty) {
                    showToast(R.string.msg_forget_select_shop);
                    return;
                }
                CommonUtils.showProgressDialog(WasteActivity.this);
                Map<String, String> data = new HashMap<>();
                data.put("token", CommonUtils.getToken(WasteActivity.this));
                data.put("data", DPGsonUtil.toJson(listData.getWaste()));
                data.put("uid", extra.substring(extra.indexOf("=") + 1));
                DPLogUtil.d("uid=" + extra.substring(extra.indexOf("=") + 1));
                HttpUtil.httpPostWithParams(WasteActivity.this, 1, Consts.Apis.POST_FP_MAKER_ORDER, data, httpCallBack);


            }
        });

        expand_list.setGroupIndicator(null);

        LayoutInflater inflater = LayoutInflater.from(this);
        View headView = inflater.inflate(R.layout.head_view, null);

        expand_list.addHeaderView(headView);

//        View footView = inflater.inflate(R.layout.one_dp_view, null);
//        expand_list.addFooterView(footView);

        nick_name = (TextView) headView.findViewById(R.id.nickname);
        score = (TextView) headView.findViewById(R.id.score);
        avatar = (DPCircleImageView) headView.findViewById(R.id.avatar);


        // 这里是控制只有一个group展开的效果
//        expand_list.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
//            @Override
//            public void onGroupExpand(int groupPosition) {
//                for (int i = 0; i < detailGoodsAdapter.getGroupCount(); i++)  {
//                    if (groupPosition != i) {
//                        expand_list.collapseGroup(i);
//                    }
//                }
//            }
//        });
        expand_list.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {

                if (openGroup == -1) {
                    expand_list.expandGroup(groupPosition);
                    expand_list.setSelection(groupPosition);
                    openGroup = groupPosition;
                } else if (openGroup == groupPosition) {
                    expand_list.collapseGroup(openGroup);
                    openGroup = -1;
                } else {
                    expand_list.collapseGroup(openGroup);
                    expand_list.expandGroup(groupPosition);
                    expand_list.setSelection(groupPosition);
                    openGroup = groupPosition;
                }
                return true;
            }
        });

//焦点
        expand_list.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {

            @Override
            public void onGroupCollapse(int groupPosition) {
                InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (getWindow().getCurrentFocus() != null) {
                    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                    getCurrentFocus().clearFocus();
                }
            }
        });

        expand_list.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {

            @Override
            public void onGroupExpand(int groupPosition) {
                InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (getWindow().getCurrentFocus() != null) {
                    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                    getCurrentFocus().clearFocus();
                }
            }
        });

        expand_list.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (getCurrentFocus() != null) {
                    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                    getCurrentFocus().clearFocus();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            }

        });

        postHttp();

    }

    private void postHttp() {
        Map<String, String> data = new HashMap<>();
        data.put("token", CommonUtils.getToken(this));
        data.put("msg", extra);
        HttpUtil.httpPostWithParams(WasteActivity.this, 0, Consts.Apis.POST_SCAN_FP, data, httpCallBack);
    }


    public class AdapterListView extends BaseExpandableListAdapter {
        private List<AfterCodeGsonData.Waste> listData;
        private LayoutInflater mInflater;
        private int index = -1, groupIndex = -1;

        public AdapterListView(Context context, AfterCodeGsonData.Result src) {
            listData = src.getWaste();
            mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        //得到子item需要关联的数据
        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return (listData.get(childPosition).getChildren());
        }

        //得到子item的ID
        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        //设置子item的组件
        @Override
        public View getChildView(final int groupPosition, final int childPosition,
                                 boolean isLastChild, View convertView, ViewGroup parent) {
            ChildViewHolder childViewHolder = null;

            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item_detail_receiving_into_child1, null);

                childViewHolder = new ChildViewHolder();

                childViewHolder.init(convertView);

            } else {
                childViewHolder = (ChildViewHolder) convertView.getTag();
            }

            childViewHolder.setData(listData.get(groupPosition).getChildren().get(childPosition));

            childViewHolder.valueEditTextExt.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {

                    if (event.getAction() == MotionEvent.ACTION_UP) {
                        index = childPosition;
                        groupIndex = groupPosition;
                    }
                    return false;
                }
            });

            childViewHolder.valueEditTextExt.clearFocus();

            if (index != -1 && index == childPosition && groupIndex != -1 && groupIndex == groupPosition) {

                // 如果当前的行下标和点击事件中保存的index一致，手动为EditText设置焦点。

                childViewHolder.valueEditTextExt.requestFocus();
            }
            return convertView;
        }

        //获取当前父item下的子item的个数
        @Override
        public int getChildrenCount(int groupPosition) {
            return listData.get(groupPosition).getChildren().size();
        }

        //获取当前父item的数据
        @Override
        public Object getGroup(int groupPosition) {
            return listData.get(groupPosition);
        }

        @Override
        public int getGroupCount() {
            return listData.size();
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        //设置父item组件
        @Override
        public View getGroupView(int groupPosition, boolean isExpanded,
                                 View convertView, ViewGroup parent) {
            convertView = mInflater.inflate(R.layout.item_detail_receiving_group, null);
            TextView firstName = (TextView) convertView.findViewById(R.id.groupName);
            firstName.setText(listData.get(groupPosition).getName());

            ImageView parentRightImage = (ImageView) convertView.findViewById(R.id.parentRightImage);
            ImageView parentLeftImage = (ImageView) convertView.findViewById(R.id.parentLeftImage);

            DPPicassoUtil.with(WasteActivity.this).load(listData.get(groupPosition).getImg()).into(parentLeftImage);
            if (isExpanded) {
                parentRightImage.setRotation(90);
            } else {
                parentRightImage.setRotation(0);
            }
            return convertView;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

        public class ChildViewHolder implements View.OnClickListener {

            public AfterCodeGsonData.Children src;

            public TextView nameTextView, score;
            public TextView priceTextView;
            public ImageView increaceImageView;
            public EditTextExt valueEditTextExt;
            public ImageView decreaceImageView;
            public TextView unitTextView;
            public TextView showTextView;
            public LinearLayout editAreaLinearLayout;


            public ChildViewHolder() {

            }

            public void init(View convertView) {
                convertView.setTag(this);

                score = (TextView) convertView.findViewById(R.id.score);
                nameTextView = (TextView) convertView.findViewById(R.id.name);
                priceTextView = (TextView) convertView.findViewById(R.id.price);
                increaceImageView = (ImageView) convertView.findViewById(R.id.increace);
                valueEditTextExt = (EditTextExt) convertView.findViewById(R.id.value);
                decreaceImageView = (ImageView) convertView.findViewById(R.id.decreace);
                unitTextView = (TextView) convertView.findViewById(R.id.unit);
                showTextView = (TextView) convertView.findViewById(R.id.show);
                editAreaLinearLayout = (LinearLayout) convertView.findViewById(R.id.edit_area);

//                if (2 == status || 3 == status) {
//                    showTextView.setVisibility(View.VISIBLE);
//                    editAreaLinearLayout.setVisibility(View.GONE);
//                } else {
//                    showTextView.setVisibility(View.GONE);
//                    editAreaLinearLayout.setVisibility(View.VISIBLE);
//                }

                valueEditTextExt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        if (hasFocus) {
                            valueEditTextExt.setSelection(valueEditTextExt.getText().length());
                            valueEditTextExt.setCursorVisible(true);
                        } else {
                            valueEditTextExt.setCursorVisible(false);
                        }
                    }
                });

                valueEditTextExt.setOnTextChangedListener(new EditTextExt.OnTextChangedListener() {
                    @Override
                    public void beforeTextChanged(EditTextExt editTextExt, CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void afterTextChanged(EditTextExt editTextExt, Editable s) {
                        if (null != src) {
                            if ("".equals(editTextExt.getText().toString())) {
                                src.setQty("0");
                            } else {
                                src.setQty(String.valueOf(Long.parseLong(editTextExt.getText().toString())));
                            }
                        }
                    }

                    @Override
                    public void onTextChanged(EditTextExt editTextExt, CharSequence s, int start, int count) {

                    }
                });

                valueEditTextExt.setText("0");
                valueEditTextExt.setSelection(1);

                increaceImageView.setOnClickListener(this);
                decreaceImageView.setOnClickListener(this);
            }

            public void setData(AfterCodeGsonData.Children src) {
                if (null == src) {
                    DPLogUtil.e("src = null.");
                    return;
                }
                this.src = src;
                this.nameTextView.setText(src.getName());
                this.score.setText(src.getScore() + "积分/个");
//                this.priceTextView.setText(src.getPrice() + "元" + "/" + src.getUnit());

                this.valueEditTextExt.setText(String.valueOf(src.getQty()));

//                this.showTextView.setText(String.valueOf(src.getQty()));
            }

            @Override
            public void onClick(View v) {
                long n = 0;
                try {
                    n = Long.parseLong(valueEditTextExt.getText().toString());
                } catch (Exception e) {

                }
                if (v.getId() == R.id.increace) {
                    if (n < 1000) {
                        n++;
                    }
                } else if (v.getId() == R.id.decreace) {
                    if (n > 0) {
                        n--;
                    }
                }
                valueEditTextExt.setText(String.valueOf(n));
                valueEditTextExt.requestFocus();
            }
        }
    }
}
